package com.cloud;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author LHT
 **/

@Component
public class GlobalFallback implements FallbackProvider {
    /**
     * 这里配置是为哪个服务提供回退，*号代表所有服务
     */
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String getRoute() {
        return "*";
    }

    /**
     * 回退返回
     */
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            @NonNull
            public HttpStatus getStatusCode() {
                logger.info("路由：{},{}",route,cause);
                return HttpStatus.BAD_REQUEST;
            }

            @Override
            public int getRawStatusCode() {
                return HttpStatus.BAD_REQUEST.value();
            }

            @Override
            @NonNull
            public String getStatusText() {
                return HttpStatus.BAD_REQUEST.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            @NonNull
            public InputStream getBody() {

                return new ByteArrayInputStream("网络开小差了请稍后再试".getBytes(StandardCharsets.UTF_8));
            }

            @Override
            @NonNull
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.setContentType(MediaType.APPLICATION_JSON);
                return httpHeaders;
            }
        };
    }
}
